#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright @ 2014 OPS, Qunar Inc. (qunar.com)
#
# Author: tingfang.bao <tingfang.bao@qunar.com>
# DateTime: 15-3-11 下午3:08
from flask import Flask


class HttpMethodOverrideMiddleware(object):
    allowed_methods = [
        "GET",
        "HEAD",
        "POST",
        "DELETE",
        "PUT",
        "PATCH",
        "OPTIONS"
    ]

    bodyless_methods = ['GET', 'HEAD', 'OPTIONS', 'DELETE']

    def __init__(self, app):
        self.app = app

    def __call__(self, environ, start_response):
        method = environ.get('HTTP_X_HTTP_METHOD_OVERRIDE', '').upper()
        if method in self.allowed_methods:
            method = method.encode('ascii', 'replace')
            environ['REQUEST_METHOD'] = method
        if method in self.bodyless_methods:
            environ['CONTENT_LENGTH'] = 0
        return self.app(environ, start_response)

# 使用
app = Flask(__name__)

app.wsgi_app = HttpMethodOverrideMiddleware(app.wsgi_app)